<template>
  <div class="record-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="20" />
      </div>
      <h1 class="header-title">币种流水</h1>
      <div class="filter-button" @click="showFilterPopup">
        <van-icon name="filter-o" size="20" />
      </div>
    </div>
    
    <!-- 币种选择 -->
     <div class="currency-selector">
      <div 
        v-for="item in currencyOptions" 
        :key="item.value"
        :class="['currency-item', selectedCurrency === item.value ? 'active' : '']"
        @click="selectCurrency(item.value)"
      >
        <div class="currency-icon">
          {{ item.icon.substring(0, 3).toUpperCase() }}
        </div>
        <div class="currency-name">{{ item.label }}</div>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-card" v-if="selectedCurrency !== 'all'">
      <div class="stats-header">
        <span class="stats-title">
          {{ selectedCurrencyLabel }}
          流水统计
        </span>
        <div class="stats-period">
          <span class="period-label">{{ currentPeriodText }}</span>
          <van-icon name="arrow-down" class="period-icon" @click="showPeriodPopup = true" />
        </div>
      </div>
      
      <div class="stats-content">
        <div class="stats-item">
          <div class="stats-value income">+{{ formatNumber(statistics.income) }}</div>
          <div class="stats-label">总收入</div>
        </div>
        <div class="stats-divider"></div>
        <div class="stats-item">
          <div class="stats-value expense">-{{ formatNumber(statistics.expense) }}</div>
          <div class="stats-label">总支出</div>
        </div>
      </div>
    </div>
    
    <!-- 流水类型筛选 -->
    <div class="type-filter">
      <div 
        v-for="item in typeOptions" 
        :key="item.value"
        :class="['filter-tab', selectedType === item.value ? 'active' : '']"
        @click="selectType(item.value)"
      >
        {{ item.label }}
      </div>
    </div>
    
    <!-- 流水记录列表 -->
    <div class="record-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <!-- 日期分组 -->
          <div v-for="(group, date) in groupedRecords" :key="date" class="record-group">
            <div class="date-header" v-if="selectedCurrency !== 'all'">
              <span class="date-text">{{ formatGroupDate(date) }}</span>
              <span class="date-summary">
                收入: <span class="income-text">+{{ formatNumber(group.income) }}</span> 
                支出: <span class="expense-text">-{{ formatNumber(group.expense) }}</span>
              </span>
            </div>
            
            <!-- 记录项 -->
            <div 
              v-for="record in group.items" 
              :key="record.id"
              class="record-item"
              @click="showRecordDetail(record)"
            >
              <div 
                class="record-icon" 
                :class="getIconClass(record.tradeTyp)"
              >
                <van-icon :name="getIconName(record.tradeTyp)" />
              </div>
              
              <div class="record-info">
                <div class="record-top">
                  <span class="record-title">{{ getRecordTitle(record.tradeTyp) }}</span>
                  <span :class="['record-amount', getAmountClass(record.flowTyp)]">
                    {{ getAmountPrefix(record.flowTyp) }}{{ formatNumber(record.amount) }} {{ record.accTyp }}
                  </span>
                </div>
                
                <div class="record-bottom">
                  <span class="record-time">{{ record.createdAt }}</span>
                  <span :class="['record-status', getAmountClass(record.flowTyp)]">
                    {{ getFlowTypText(record.flowTyp) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <van-empty 
            v-if="records.length === 0 && !loading && finished" 
            description="暂无流水记录" 
          />
        </van-list>
      </van-pull-refresh>
    </div>
    
    <!-- 筛选弹窗 -->
    <van-popup
      v-model:show="showFilter"
      position="bottom"
      round
      closeable
      close-icon="close"
      :style="{ height: '60%' }"
    >
      <div class="filter-popup">
        <div class="popup-title">筛选</div>
        
        <div class="filter-section">
          <h3 class="filter-section-title">币种</h3>
          <div class="filter-options">
            <div 
              v-for="item in currencyOptions" 
              :key="item.value"
              :class="['filter-option', popupFilters.currency === item.value ? 'selected' : '']"
              @click="popupFilters.currency = item.value"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
        
        <div class="filter-section">
          <h3 class="filter-section-title">流水类型</h3>
          <div class="filter-options">
            <div 
              v-for="item in flowTypOptions" 
              :key="item.value"
              :class="['filter-option', popupFilters.flowTyp === item.value ? 'selected' : '']"
              @click="popupFilters.flowTyp = item.value"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
        
        <div class="filter-section">
          <h3 class="filter-section-title">交易类型</h3>
          <div class="filter-options">
            <div 
              v-for="item in tradeTypOptions" 
              :key="item.value"
              :class="['filter-option', popupFilters.tradeTyp === item.value ? 'selected' : '']"
              @click="popupFilters.tradeTyp = item.value"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
        
        <div class="filter-section">
          <h3 class="filter-section-title">时间范围</h3>
          <div class="date-picker">
            <van-cell title="开始日期" :value="formatDate(popupFilters.startDate)" @click="showStartDatePicker = true" />
            <van-cell title="结束日期" :value="formatDate(popupFilters.endDate)" @click="showEndDatePicker = true" />
          </div>
        </div>
        
        <div class="filter-actions">
          <van-button plain block @click="resetFilters">重置</van-button>
          <van-button type="primary" block @click="applyFilters">确认</van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 周期选择弹窗 - 简化版 -->
    <van-popup
      v-model:show="showPeriodPopup"
      position="bottom"
      round
    >
      <div class="period-selector">
        <div class="period-title">选择统计周期</div>
        <div class="period-options">
          <div 
            v-for="option in periodOptions" 
            :key="option.value"
            :class="['period-option', currentPeriod === option.value ? 'active' : '']"
            @click="selectPeriodAndClose(option.value)"
          >
            {{ option.text }}
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 日期选择器 -->
    <van-calendar
      v-model:show="showStartDatePicker"
      @confirm="onStartDateConfirm"
      :min-date="minDate"
      :max-date="maxDate"
    />
    
    <van-calendar
      v-model:show="showEndDatePicker"
      @confirm="onEndDateConfirm"
      :min-date="minDate"
      :max-date="maxDate"
    />
    
    <!-- 记录详情弹窗 -->
    <van-popup
      v-model:show="showDetail"
      position="bottom"
      round
      closeable
      close-icon="close"
      :style="{ height: '70%' }"
    >
      <div class="record-detail" v-if="currentRecord">
        <div class="detail-header">
          <h2 class="detail-title">流水详情</h2>
        </div>
        
        <div class="detail-amount-section">
          <div :class="['detail-amount', getAmountClass(currentRecord.flowTyp)]">
            {{ getAmountPrefix(currentRecord.flowTyp) }}{{ currentRecord.amount }} {{ currentRecord.accTyp }}
          </div>
          <div :class="['detail-status', getStatusClass(currentRecord.status)]">
            {{ getStatusText(currentRecord.status) }}
          </div>
        </div>
        
        <div class="detail-info-list">
          <div class="detail-info-item">
            <span class="info-label">流水类型</span>
            <span class="info-value">{{ getFlowTypText(currentRecord.flowTyp) }}</span>
          </div>
          
          <div class="detail-info-item">
            <span class="info-label">交易类型</span>
            <span class="info-value">{{ getRecordTitle(currentRecord.tradeTyp) }}</span>
          </div>
          
          <div class="detail-info-item">
            <span class="info-label">交易时间</span>
            <span class="info-value">{{ currentRecord.time }}</span>
          </div>
          
          <div class="detail-info-item">
            <span class="info-label">交易单号</span>
            <span class="info-value copy-value" @click="copyText(currentRecord.id)">
              {{ currentRecord.id }}
              <van-icon name="copy-o" />
            </span>
          </div>
          
          <div class="detail-info-item" v-if="currentRecord.hash">
            <span class="info-label">交易哈希</span>
            <span class="info-value copy-value" @click="copyText(currentRecord.hash)">
              {{ formatHash(currentRecord.hash) }}
              <van-icon name="copy-o" />
            </span>
          </div>
          
          <div class="detail-info-item" v-if="currentRecord.address">
            <span class="info-label">关联地址</span>
            <span class="info-value copy-value" @click="copyText(currentRecord.address)">
              {{ formatAddress(currentRecord.address) }}
              <van-icon name="copy-o" />
            </span>
          </div>
          
          <div class="detail-info-item" v-if="currentRecord.fee">
            <span class="info-label">手续费</span>
            <span class="info-value">{{ currentRecord.fee }} {{ currentRecord.accTyp }}</span>
          </div>
          
          <div class="detail-info-item" v-if="currentRecord.remark">
            <span class="info-label">备注</span>
            <span class="info-value">{{ currentRecord.remark }}</span>
          </div>
        </div>
        
        <div class="detail-actions" v-if="currentRecord.hash">
          <van-button 
            type="primary" 
            block 
            @click="viewOnBlockchain(currentRecord.hash)"
          >
            在区块链浏览器中查看
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { getRecordList, getRecordStatistics, getRecordDetail} from '@/api/cash'
import { formatNumber} from '@/utils/utils'
const router = useRouter()
const route = useRoute()

// 币种选项
const currencyOptions = ref([
  { label: '全部', value: 'all', icon: '全部' },
  { label: 'USDT', value: 'USDT', icon: 'USDT' },
  { label: 'HDFS', value: 'HDFS', icon: 'HDFS' },
])

// 流水类型选项 (收入/支出)
const flowTypOptions = [
  { label: '全部', value: '' },
  { label: '收入', value: '1' },
  { label: '支出', value: '2' }
]

// 类型选项 (用于顶部筛选栏)
const typeOptions = ref([
  { label: '全部', value: 'all' },
  { label: '收入', value: 'income' },
  { label: '支出', value: 'expense' }
])

// 交易类型选项
const tradeTypOptions = [
  { label: '全部', value: '' },
  { label: '充值', value: '1' },
  { label: '提现', value: '2' },
  { label: '转账', value: '3' },
  { label: '消费', value: '4' },
  { label: '退款', value: '5' },
  { label: '佣金', value: '6' },
  { label: '项目参与', value: '7' },
  { label: '购买商品', value: '8' },
  { label: '项目赎回', value: '9' },
]

// 状态选项
const statusOptions = [
  { label: '全部状态', value: 'all' },
  { label: '已完成', value: 'completed' },
  { label: '处理中', value: 'pending' },
  { label: '失败', value: 'failed' }
]

// 周期选项
const periodOptions = [
  { text: '今日', value: 'today' },
  { text: '本周', value: 'week' },
  { text: '本月', value: 'month' },
  { text: '上月', value: 'lastMonth' },
  { text: '今年', value: 'year' }
]

// 列表状态
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = ref(10)

// 筛选状态
const selectedCurrency = ref(route.query.currency || 'all')
const selectedType = ref(route.query.type || 'all')
const showFilter = ref(false)
const popupFilters = ref({
  currency: '',
  flowTyp: '',
  tradeTyp: '',
  status: '',
  startDate: null,
  endDate: null
})

// 统计周期
const currentPeriod = ref('month') // 默认为本月
const showPeriodPopup = ref(false)

// 日期选择器
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)
const minDate = new Date(new Date().getFullYear() - 1, 0, 1)
const maxDate = new Date()

// 记录详情
const showDetail = ref(false)
const currentRecord = ref(null)

// 统计数据
const statistics = ref({
  income: '0.00',
  expense: '0.00'
})

// 记录数据
const records = ref([])

// 按日期分组的记录
const groupedRecords = computed(() => {
  const filtered = records.value.filter(record => {
    // 币种筛选
    if (selectedCurrency.value !== 'all' && selectedCurrency.value !== '' && record.accTyp !== selectedCurrency.value) {
      return false
    }
    
    // 类型筛选
    if (selectedType.value !== 'all' && selectedType.value !== '') {
      if (selectedType.value === 'income' && record.flowTyp !== '1') {
        return false
      }
      if (selectedType.value === 'expense' && record.flowTyp !== '2') {
        return false
      }
    }
    
    return true
  })
  
  // 按日期分组
  const groups = {}
  
  filtered.forEach(record => {
    // 提取日期部分
    const datePart = record.createdAt ? record.createdAt.split(' ')[0] : '未知日期'
    
    if (!groups[datePart]) {
      groups[datePart] = {
        items: [],
        income: 0,
        expense: 0
      }
    }
    
    groups[datePart].items.push(record)
    
    // 计算每日收支
    if (record.flowTyp === '1') { // 收入
      groups[datePart].income += parseFloat(record.amount || 0)
    } else if (record.flowTyp === '2') { // 支出
      groups[datePart].expense += parseFloat(record.amount || 0)
    }
  })
  
  // 格式化收支金额
  Object.keys(groups).forEach(date => {
    groups[date].income = groups[date].income.toFixed(2)
    groups[date].expense = groups[date].expense.toFixed(2)
  })
  
  return groups
})

// 获取选中币种的标签
const selectedCurrencyLabel = computed(() => {
  const currency = currencyOptions.value.find(c => c.value === selectedCurrency.value)
  return currency ? currency.label : '全部币种'
})

// 选择币种
const selectCurrency = (currency) => {
  selectedCurrency.value = currency
  // 更新URL参数
  updateUrlParams()
  // 重置分页
  page.value = 1
  finished.value = false
  // 清空记录列表
  records.value = []
  
  // 显示加载提示
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  // 如果选择了特定币种（非全部），需要同时请求统计数据和记录数据
  if (currency !== 'all' && currency !== '') {
    // 请求统计数据
    calculateStatistics().finally(() => {
      // 加载记录数据
      loadRecords().finally(() => {
        closeToast()
      })
    })
  } else {
    // 选择全部币种时，只加载记录数据
    loadRecords().finally(() => {
      closeToast()
    })
  }
}

// 选择类型
const selectType = (type) => {
  selectedType.value = type
  // 更新URL参数
  updateUrlParams()
  // 重置分页
  page.value = 1
  finished.value = false
  // 清空记录列表
  records.value = []
  
  // 显示加载提示
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  // 直接加载记录数据，不请求统计数据（筛选条件变化时不调用统计接口）
  loadRecords().finally(() => {
    closeToast()
  })
}

// 更新URL参数
const updateUrlParams = () => {
  router.replace({
    query: {
      ...route.query,
      currency: selectedCurrency.value,
      type: selectedType.value
    }
  })
}

// 计算统计数据
const calculateStatistics = () => {
  // 如果选择的是全部币种，不请求统计数据
  if (selectedCurrency.value === '' || selectedCurrency.value === 'all') {
    return Promise.resolve();
  }
  
  // 构建请求参数
  const params = {
    accTyp: selectedCurrency.value,
    period: currentPeriod.value || 'month' // 确保period始终有值，默认为month
  }
  
  // 如果选择了特定类型（收入/支出），添加到请求参数
  if (selectedType.value === 'income') {
    params.flowTyp = '1'
  } else if (selectedType.value === 'expense') {
    params.flowTyp = '2'
  }
  
  console.log('请求统计数据参数:', params)
  
  return getRecordStatistics(params).then(res => {
    if (res.code === 0) {
      statistics.value = {
        income: res.data.totalIn,
        expense: res.data.totalOut
      }
    } else {
      // 接口返回错误码时，显示错误信息
      showToast(res.message || '获取统计数据失败')
      // 使用默认值
      statistics.value = {
        income: '0.00',
        expense: '0.00'
      }
    }
  }).catch(err => {
    console.error('获取统计数据失败', err)
    showToast('获取统计数据失败')
    // 使用默认值
    statistics.value = {
      income: '0.00',
      expense: '0.00'
    }
  }).finally(() => {
    closeToast()
  })
}

// 下拉刷新
const onRefresh = () => {
  // 如果正在加载，不执行刷新
  if (loading.value) {
    refreshing.value = false
    return
  }
  
  // 重置状态
  page.value = 1
  finished.value = false
  records.value = [] // 清空记录列表，避免数据重复
  
  // 设置一个超时，防止长时间加载
  const timeout = setTimeout(() => {
    if (refreshing.value) {
      refreshing.value = false
      showToast('刷新超时，请稍后再试')
    }
  }, 10000) // 10秒超时
  
  // 显示加载提示
  showLoadingToast({
    message: '刷新中...',
    forbidClick: true,
  })
  
  // 如果是特定币种，同时刷新统计数据和记录数据
  if (selectedCurrency.value !== 'all' && selectedCurrency.value !== '') {
    calculateStatistics().finally(() => {
      loadRecords().then(() => {
        clearTimeout(timeout)
        refreshing.value = false
        showToast('刷新成功')
      }).catch(() => {
        clearTimeout(timeout)
        refreshing.value = false
        showToast('刷新失败')
        // 刷新失败时，标记为已完成，避免继续请求
        finished.value = true
      }).finally(() => {
        closeToast()
      })
    })
  } else {
    // 全部币种只刷新记录数据
    loadRecords().then(() => {
      clearTimeout(timeout)
      refreshing.value = false
      showToast('刷新成功')
    }).catch(() => {
      clearTimeout(timeout)
      refreshing.value = false
      showToast('刷新失败')
      // 刷新失败时，标记为已完成，避免继续请求
      finished.value = true
    }).finally(() => {
      closeToast()
    })
  }
}

// 上拉加载
const onLoad = () => {
  // 防止重复加载
  if (loading.value) return
  loadRecords()
}

// 加载记录数据
const loadRecords = () => {
  if (finished.value) return Promise.resolve()
  
  loading.value = true
  
  const params = {
    page: page.value,
    size: pageSize.value,
    accTyp: selectedCurrency.value === 'all' || selectedCurrency.value === '' ? '' : selectedCurrency.value,
    flowTyp: selectedType.value === 'income' ? '1' : selectedType.value === 'expense' ? '2' : '',
    tradeTyp: popupFilters.value.tradeTyp,
    startTime: popupFilters.value.startDate ? formatDate(popupFilters.value.startDate) : null,
    endTime: popupFilters.value.endDate ? formatDate(popupFilters.value.endDate) : null
  }
  
  // 移除周期参数，避免重复请求
  
  return getRecordList(params).then(res => {
    if (res.code === 0) {
      const newRecords = res.data.list || []
      
      if (page.value === 1) {
        records.value = newRecords
      } else {
        records.value = [...records.value, ...newRecords]
      }
      
      page.value++
      
      // 判断是否加载完成
      if (newRecords.length < pageSize.value || records.value.length >= (res.data.count || 0)) {
        finished.value = true
      }
    } else {
      // 接口返回错误码时，标记为加载完成，避免继续请求
      finished.value = true
      showToast(res.message || '加载失败')
    }
  }).catch(err => {
    console.error('获取记录列表失败', err)
    showToast('加载失败，请重试')
    // 发生错误时，标记为加载完成，避免继续请求
    finished.value = true
  }).finally(() => {
    loading.value = false
  })
}

// 显示筛选弹窗
const showFilterPopup = () => {
  // 初始化弹窗筛选条件
  popupFilters.value = {
    currency: selectedCurrency.value,
    flowTyp: selectedType.value === 'income' ? '1' : selectedType.value === 'expense' ? '2' : '',
    tradeTyp: '',
    status: 'all',
    startDate: null,
    endDate: null
  }
  showFilter.value = true
}

// 重置筛选条件
const resetFilters = () => {
  popupFilters.value = {
    currency: 'all',
    flowTyp: '',
    tradeTyp: '',
    status: 'all',
    startDate: null,
    endDate: null
  }
}

// 应用筛选条件
const applyFilters = () => {
  // 记录之前的币种
  const prevCurrency = selectedCurrency.value
  
  selectedCurrency.value = popupFilters.value.currency
  
  // 根据流水类型设置selectedType
  if (popupFilters.value.flowTyp === '1') {
    selectedType.value = 'income'
  } else if (popupFilters.value.flowTyp === '2') {
    selectedType.value = 'expense'
  } else {
    selectedType.value = 'all'
  }
  
  // 更新URL参数
  updateUrlParams()
  
  // 关闭弹窗
  showFilter.value = false
  
  // 重置分页
  page.value = 1
  finished.value = false
  // 清空记录列表
  records.value = []
  
  // 显示加载提示
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  // 如果币种从全部变为特定币种，需要请求统计数据
  if (prevCurrency === 'all' && selectedCurrency.value !== 'all' && selectedCurrency.value !== '') {
    calculateStatistics().finally(() => {
      loadRecords().finally(() => {
        closeToast()
      })
    })
  } else {
    // 其他情况只加载记录数据
    loadRecords().finally(() => {
      closeToast()
    })
  }
}

// 选择周期并关闭弹窗
const selectPeriodAndClose = (period) => {
  currentPeriod.value = period
  showPeriodPopup.value = false
  
  // 只有在选择了特定币种时才加载统计数据
  if (selectedCurrency.value !== 'all' && selectedCurrency.value !== '') {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
    })
    
    // 只重新加载统计数据，不重新加载记录数据
    calculateStatistics().finally(() => {
      closeToast()
    })
  }
}

// 保留原来的selectPeriod函数以兼容可能的其他调用
const selectPeriod = (period) => {
  currentPeriod.value = period
  
  // 只有在选择了特定币种时才加载统计数据
  if (selectedCurrency.value !== 'all' && selectedCurrency.value !== '') {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
    })
    
    // 只重新加载统计数据，不重新加载记录数据
    calculateStatistics().finally(() => {
      closeToast()
    })
  }
}

// 保留原有的onPeriodConfirm函数以兼容可能的其他调用
const onPeriodConfirm = (value) => {
  // 确保value是有效的对象并且有value属性
  if (value && typeof value === 'object' && value.value) {
    selectPeriodAndClose(value.value)
  } else {
    // 如果value无效，使用默认值'month'
    selectPeriodAndClose('month')
  }
}

// 日期选择器确认
const onStartDateConfirm = (date) => {
  popupFilters.value.startDate = date
  showStartDatePicker.value = false
}

const onEndDateConfirm = (date) => {
  popupFilters.value.endDate = date
  showEndDatePicker.value = false
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '请选择'
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化分组日期
const formatGroupDate = (dateStr) => {
  const date = new Date(dateStr)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  if (dateStr === today.toISOString().split('T')[0]) {
    return '今天'
  } else if (dateStr === yesterday.toISOString().split('T')[0]) {
    return '昨天'
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const parts = timeStr.split(' ');
  return parts.length > 1 ? parts[1] : timeStr;
}

// 显示记录详情
const showRecordDetail = (record) => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  getRecordDetail(record.id).then(res => {
    if (res.code === 0) {
      currentRecord.value = res.data
      showDetail.value = true
    } else {
      // 接口返回错误码时，使用列表中的记录数据
      showToast(res.message || '获取详情失败')
      currentRecord.value = record
      showDetail.value = true
    }
  }).catch(err => {
    console.error('获取记录详情失败', err)
    showToast('获取详情失败，显示基本信息')
    currentRecord.value = record
    showDetail.value = true
  }).finally(() => {
    closeToast()
  })
}

// 获取图标类名
const getIconClass = (tradeTyp) => {
  const iconMap = {
    '1': 'icon-deposit',      // 充值
    '2': 'icon-withdraw',     // 提现
    '3': 'icon-transfer-in',  // 转账
    '4': 'icon-consume',      // 消费
    '5': 'icon-refund',       // 退款
    '6': 'icon-commission',   // 佣金
    '7': 'icon-project',      // 项目参与
    '8': 'icon-goods'         // 购买商品
  }
  return iconMap[tradeTyp] || 'icon-default'
}

// 获取图标名称
const getIconName = (tradeTyp) => {
  const iconMap = {
    '1': 'peer-pay',          // 充值
    '2': 'cash-back-record',  // 提现
    '3': 'exchange',          // 转账
    '4': 'shopping-cart-o',   // 消费
    '5': 'after-sale',        // 退款
    '6': 'gold-coin-o',       // 佣金
    '7': 'chart-trending-o',  // 项目参与
    '8': 'shopping-bag-o',     // 购买商品
    '9': 'chart-trending-o'     // 项目赎回
  }
  return iconMap[tradeTyp] || 'records'
}

// 获取记录标题
const getRecordTitle = (tradeTyp) => {
  const titleMap = {
    '1': '充值',
    '2': '提现',
    '3': '转账',
    '4': '消费',
    '5': '退款',
    '6': '佣金',
    '7': '项目参与',
    '8': '购买商品',
    '9': '项目赎回'
  }
  return titleMap[tradeTyp] || '其他'
}

// 获取流水类型文本
const getFlowTypText = (flowTyp) => {
  return flowTyp === '1' ? '收入' : flowTyp === '2' ? '支出' : '未知'
}

// 获取金额前缀
const getAmountPrefix = (flowTyp) => {
  return flowTyp === '1' ? '+' : flowTyp === '2' ? '-' : ''
}

// 获取金额样式类
const getAmountClass = (flowTyp) => {
  return flowTyp === '1' ? 'amount-increase' : flowTyp === '2' ? 'amount-decrease' : 'amount-neutral'
}

// 获取状态文本
const getStatusText = (status) => {
  return {
    'completed': '已完成',
    'pending': '处理中',
    'failed': '失败'
  }[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  return {
    'completed': 'status-completed',
    'pending': 'status-pending',
    'failed': 'status-failed'
  }[status] || ''
}

// 格式化地址显示
const formatAddress = (address) => {
  if (!address) return ''
  return address.substring(0, 6) + '...' + address.substring(address.length - 4)
}

// 格式化哈希显示
const formatHash = (hash) => {
  if (!hash) return ''
  return hash.substring(0, 10) + '...' + hash.substring(hash.length - 6)
}

// 复制文本
const copyText = (text) => {
  navigator.clipboard.writeText(text)
  showToast('已复制')
}

// 在区块链浏览器中查看
const viewOnBlockchain = (hash) => {
  window.open(`https://etherscan.io/tx/${hash}`, '_blank')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取当前周期的显示文本
const currentPeriodText = computed(() => {
  const period = periodOptions.find(p => p.value === currentPeriod.value)
  return period ? period.text : '本月'
})

// 初始化
onMounted(() => {
  // 如果有URL参数，应用筛选条件，否则使用默认值'all'
  selectedCurrency.value = route.query.currency || 'all'
  selectedType.value = route.query.type || 'all'
  
  // 更新URL参数，确保URL与当前选择一致
  updateUrlParams()
  
  // 显示加载提示
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  // 只有当选择了特定币种时，才加载统计数据
  if (selectedCurrency.value !== 'all' && selectedCurrency.value !== '') {
    calculateStatistics().finally(() => {
      // 加载记录数据
      loadRecords().finally(() => {
        closeToast()
      })
    })
  } else {
    // 直接加载记录数据
    loadRecords().finally(() => {
      closeToast()
    })
  }
})
</script>

<style scoped>
.record-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 24px;
  max-width: 800px;
  margin: 0 auto;
}

/* 顶部导航 */
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  max-width: 800px;
  margin: 0 auto;
}

.back-button, .filter-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  cursor: pointer;
  color: #334155;
  background: transparent;
  border: none;
  padding: 0;
}

.header-title {
  flex: 1;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  text-align: center;
}

  /* 币种选择器 */
.currency-selector {
  display: flex;
  overflow-x: auto;
  padding: 16px;
  background-color: #ffffff;
  margin: 12px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 56px;
  z-index: 99;
  max-width: 776px;
  margin-left: auto;
  margin-right: auto;
  border-radius: 8px;
  border: 1px solid #f1f5f9;
}

.currency-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  margin-right: 12px;
  cursor: pointer;
  min-width: 80px;
  border-radius: 8px;
  transition: all 0.2s;
}

.currency-item:last-child {
  margin-right: 0;
}

.currency-item:hover {
  background-color: #f8fafc;
}

.currency-icon {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #1989fa, #0066cc);
  color: white;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.2);
  letter-spacing: 0.5px;
}

.currency-name {
  font-size: 14px;
  color: #64748b;
  transition: all 0.2s;
}

.currency-item.active {
  background-color: #eff6ff;
  border: 1px solid #3b82f6;
}

.currency-item.active .currency-icon {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
}

.currency-item.active .currency-name {
  color: #1989fa;
  font-weight: 500;
}

/* 统计卡片 */
.stats-card {
  background-color: #ffffff;
  border-radius: 12px;
  margin: 0 12px 16px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #334155;
}

.stats-type {
  font-size: 14px;
  color: #64748b;
  font-weight: normal;
}

.stats-period {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #64748b;
  cursor: pointer;
  background-color: #f1f5f9;
  padding: 4px 10px;
  border-radius: 16px;
}

.period-label {
  margin-right: 4px;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 16px 0;
  background-color: #f8fafc;
  border-radius: 8px;
}

.stats-item {
  flex: 1;
  text-align: center;
}

.stats-divider {
  width: 1px;
  height: 40px;
  background-color: #e2e8f0;
}

.stats-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

.stats-value.income {
  color: #10b981;
}

.stats-value.expense {
  color: #ef4444;
}

.stats-label {
  font-size: 14px;
  color: #64748b;
}

/* 流水类型筛选 */
.type-filter {
  display: flex;
  padding: 12px 16px;
  background-color: #ffffff;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  margin-left: 12px;
  margin-right: 12px;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  color: #64748b;
  background-color: #f1f5f9;
  margin-right: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-tab:last-child {
  margin-right: 0;
}

.filter-tab.active {
  color: #ffffff;
  background: linear-gradient(135deg, #1989fa, #0066cc);
  box-shadow: 0 2px 6px rgba(25, 137, 250, 0.2);
}

/* 流水记录列表 */
.record-list {
  padding: 0 12px;
  max-width: 800px;
  margin: 0 auto;
}

.record-group {
  margin-bottom: 16px;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background-color: #f1f5f9;
  border-radius: 8px;
  margin-bottom: 10px;
}

.date-text {
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}

.date-summary {
  font-size: 12px;
  color: #64748b;
}

.income-text {
  color: #10b981;
  margin-right: 8px;
  font-weight: 500;
}

.expense-text {
  color: #ef4444;
  font-weight: 500;
}

.record-item {
  display: flex;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 10px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.record-item:active {
  transform: scale(0.98);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.record-icon {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 14px;
  flex-shrink: 0;
}

.icon-deposit {
  background: linear-gradient(135deg, #10b981, #059669);
}

.icon-deposit .van-icon {
  color: white;
}

.icon-withdraw {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.icon-withdraw .van-icon {
  color: white;
}

.icon-transfer-in, .icon-transfer-out {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

.icon-transfer-in .van-icon, .icon-transfer-out .van-icon {
  color: white;
}

.icon-consume {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.icon-consume .van-icon {
  color: white;
}

.icon-refund {
  background: linear-gradient(135deg, #06b6d4, #0891b2);
}

.icon-refund .van-icon {
  color: white;
}

.icon-commission {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}

.icon-commission .van-icon {
  color: white;
}

.icon-project {
  background: linear-gradient(135deg, #ec4899, #db2777);
}

.icon-project .van-icon {
  color: white;
}

.icon-goods {
  background: linear-gradient(135deg, #14b8a6, #0d9488);
}

.icon-goods .van-icon {
  color: white;
}

.icon-default {
  background: linear-gradient(135deg, #64748b, #475569);
}

.icon-default .van-icon {
  color: white;
}

.record-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.record-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.record-amount {
  font-size: 16px;
  font-weight: 600;
}

.amount-increase {
  color: #10b981;
}

.amount-decrease {
  color: #ef4444;
}

.amount-neutral {
  color: #3b82f6;
}

.record-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-time {
  font-size: 14px;
  color: #64748b;
}

.record-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
}

.status-completed {
  background-color: #dcfce7;
  color: #16a34a;
}

.status-pending {
  background-color: #fef3c7;
  color: #d97706;
}

.status-failed {
  background-color: #fee2e2;
  color: #dc2626;
}

/* 收入支出状态样式 */
.record-status.amount-increase {
  background-color: #dcfce7;
  color: #16a34a;
}

.record-status.amount-decrease {
  background-color: #fee2e2;
  color: #dc2626;
}

/* 筛选弹窗 */
.filter-popup {
  padding: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  text-align: center;
  margin-bottom: 24px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-section:last-child {
  margin-bottom: 32px;
}

.filter-section-title {
  font-size: 16px;
  font-weight: 500;
  color: #334155;
  margin-bottom: 12px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-option {
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  color: #64748b;
  background-color: #f1f5f9;
  cursor: pointer;
  transition: all 0.2s;
}

.filter-option.selected {
  color: #ffffff;
  background-color: #1989fa;
}

.date-picker {
  background-color: #f8fafc;
  border-radius: 8px;
  overflow: hidden;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

/* 记录详情弹窗 */
.record-detail {
  padding: 20px;
}

.detail-header {
  text-align: center;
  margin-bottom: 24px;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.detail-amount-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}

.detail-amount {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 12px;
}

.detail-status {
  font-size: 14px;
  padding: 4px 16px;
  border-radius: 20px;
}

.detail-info-list {
  background-color: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
}

.detail-info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.detail-info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 14px;
  color: #64748b;
}

.info-value {
  font-size: 14px;
  color: #334155;
  text-align: right;
  font-weight: 500;
}

.copy-value {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.copy-value .van-icon {
  margin-left: 6px;
  color: #64748b;
}

.detail-actions {
  padding: 0 16px;
}

/* 周期选择器样式 - 简化版 */
.period-selector {
  padding: 20px;
}

.period-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  text-align: center;
  margin-bottom: 24px;
}

.period-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 24px;
}

.period-option {
  flex: 0 0 calc(33.33% - 8px);
  padding: 12px 0;
  border-radius: 8px;
  font-size: 16px;
  color: #64748b;
  background-color: #f1f5f9;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.period-option.active {
  color: #ffffff;
  background-color: #1989fa;
  font-weight: 500;
}

</style>
